package com.atguigu.day02;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @ClassName NotSafeDemo
 * @Description 此类描述:
 * @Author dangchen
 * @DateTime 2022-09-07 18:51
 * @Version 1.0
 */
public class NotSafeDemo {
    public static void main(String[] args) {

       /* //ArrayList线程不安全举例,边读边写
        //List list = new ArrayList();
        //List list = new Vector();
        //List list = Collections.synchronizedList(new ArrayList<>());
        List<String> list = new CopyOnWriteArrayList<>();
        for (int i = 1; i < 30; i++) {
            new Thread( () -> {
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(list);
            },String.valueOf(i)).start();
        }*/

        /*
        以后myerror文件格式就参考这样,并且上传码云
        1.故障现象:currentModificationException 并发修改异常
        2.导致原因:next迭代器,边写边读,导致数据不对,总数不匹配modCount != expectedModCount
        3.解决方案
            3.1 使用线程安全的类,Vector
            3.2 Collections.synchronizedList
            3.3 JUC中CopyOnWriteArrayList 读写分离+写时复制,某一时刻只能一个人在写,笔只有一支,没有锁,性能好点
         4.优化建议
         */

        //HashSet线程不安全举例
        //Set set = new HashSet();
        //Set set = Collections.synchronizedSet(new HashSet<>());
        /*Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 1; i < 30; i++) {
            new Thread( () -> {
                set.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(set);
            },String.valueOf(i)).start();
        }*/

        //HashMap线程不安全举例,边读边写
        //Map map = new HashMap();
        //Map map = Collections.synchronizedMap(new HashMap<>());
        Map<String, String> map = new ConcurrentHashMap<>();
        for (int i = 1; i < 30; i++) {
            new Thread( () -> {
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,8));
                System.out.println(map);
            },String.valueOf(i)).start();
        }
    }
}
